<template>
	<view>

		<ScrollTab :tabList="tabData" :defaultActive="0" @tabChange="onTabChange" />
		<newsWeatherVue />

		<view v-for="(item,index) in datalist" style="margin: 10rpx;">
			<CustomTextView :title="item.title" :isTop="item.isTop" :author="item.author" :comments="item.comments"
				:time="item.time" :images="item.imageList || []" :mode=item.mode @click="onCustomViewClick(index)">
				<template v-slot:tips>
					<view class="slotcontent" v-if="item.showSearch">
						<text style="color: darkblue;font-weight: bold;">搜索</text>
						<text>今日金价</text>
						<text>精选好物</text>
					</view>
				</template>
			</CustomTextView>
		</view>

	</view>
</template>

<script>
	import newsData from '../../../data/news.json'
	import ScrollTab from '../../../components/ScrollTab.vue'
	import CustomTextView from "../../../components/cardViewText.vue"
	import newsWeatherVue from '../../../components/newsWeather.vue'
	function getRandomItems(arr, count) {
	  // 创建原始数组的副本，以避免修改原始数据
	  const shuffled = [...arr];
	  //  Fisher-Yates 洗牌算法，打乱数组顺序
	  for (let i = shuffled.length - 1; i > 0; i--) {
	    const j = Math.floor(Math.random() * (i + 1));
	    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
	  }
	  // 返回打乱后的数组的前 count 个元素
	  return shuffled.slice(0, count);
	}
	export default {
		components: {
			CustomTextView,
			ScrollTab,
			newsWeatherVue
		},
		data() {
			return {

				datalist: newsData,
				tabData: ['要闻', '推荐', '关注流', '24小时', '娱乐', '桂林', '财经', '更多', '标签'],
				activeTab: ''
			}
		},
		onLoad() {

		},
		onPullDownRefresh() {
					console.log('开始下拉刷新...');
		
					// 模拟网络请求延迟，让用户能看到 loading 动画
					setTimeout(() => {
						// 1. 从原始新闻数据中随机获取 5 条
						const newItems = getRandomItems(newsData, 5);
		
						// 2. 将新获取的数据添加到 datalist 的开头
						// 使用 concat 或者展开运算符 (...) 来创建一个新数组，这是 Vue 响应式的最佳实践
						this.datalist = [...newItems, ...this.datalist];
		
						console.log('刷新成功，已添加 5 条新数据。');
		
						// 3. 关键步骤：通知 uni-app 刷新已经完成，让 loading 动画消失
						uni.stopPullDownRefresh();
		
					}, 1000); // 延迟 1 秒，模拟网络请求时间
				},
		methods: {
			onCustomViewClick(index) {
				console.log("点击了第", index + 1, "个组件");
			},
			onTabChange(e) {
				console.log('Tab changed:', e);
				this.activeTab = e.value;
				// Handle tab change logic here
			},
			goRsd() {
				uni.startPullDownRefresh({
					success() {
						console.log("start refreshing success");
					}
				})
			}
		}
	}
</script>

<style>
	.slotcontent {
		display: flex;
		align-items: center;
		font-size: 0.8rem;
	}

	.slotcontent text {

		margin-right: 10rpx;
		/* Adjust the space between text elements */
	}
</style>